/*
 * Created on Dec 3, 2004
 */
package jdbcmanager.swing.text;

import java.awt.Toolkit;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 * Class what controls if a text have Fixd Length and if is numeric. 
 */
public class FixedLengthDocument extends PlainDocument {

	   private int maxLength = 9999;
	   private boolean numericOnly;

	   public FixedLengthDocument(int maxLength) {
	   		this(maxLength, false);
	   }
	   
	   public FixedLengthDocument(int maxLength, boolean numericOnly) {
	      super();
	      this.maxLength = maxLength;
	      this.numericOnly = numericOnly;
	   }

	   //this is where we'll control all input to our document.  
	   //If the text that is being entered passes our criteria, then we'll just call
	   public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
			if (getLength() + str.length() > maxLength) {
				Toolkit.getDefaultToolkit().beep();
				return;
			} 
	         try {
	            if (numericOnly) {
	               //check if str is numeric only
	               //If not Numeric, then throws NumberFormatException
	               Double.parseDouble(str);
	            }
	            super.insertString(offset, str, attr);
	         }
	         catch(NumberFormatException exp) {
	            Toolkit.getDefaultToolkit().beep();
	            return;
	         }
	   }
	   
} //end Class